#!/bin/bash
#
# Copyright 2012 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Refer to the README and COPYING files for full details of the license
#

VDSM_PKI="@TRUSTSTORE@"
VDSM_KEY="$VDSM_PKI/keys/vdsmkey.pem"
VDSM_CRT="$VDSM_PKI/certs/vdsmcert.pem"
VDSM_CA="$VDSM_PKI/certs/cacert.pem"

VDSM_TEMPLATE="$(mktemp)"

VDSM_FQDN=`hostname -f`
[ -z "$VDSM_FQDN" ] && VDSM_FQDN="localhost.localdomain"

VDSM_PERMS="@VDSMUSER@:@VDSMGROUP@"

umask 077

if [ "$1" = "--check" ]; then
    [ -s "$VDSM_KEY" -a -s "$VDSM_CA" -a -s "$VDSM_CRT" ] && exit 0 || exit 1
fi

if [ ! -f "$VDSM_KEY" ]; then
    /usr/bin/certtool --generate-privkey --outfile "$VDSM_KEY" 2> /dev/null
    /bin/chown "$VDSM_PERMS" "$VDSM_KEY"
    /sbin/restorecon "$VDSM_KEY"
fi

if [ ! -f "$VDSM_CA" ]; then
    /bin/cat > "$VDSM_TEMPLATE" <<EOF
cn = "VDSM Certificate Authority"
ca
cert_signing_key
EOF
    /usr/bin/certtool --generate-self-signed --load-privkey  "$VDSM_KEY" \
                      --template "$VDSM_TEMPLATE" --outfile "$VDSM_CA" \
                      2> /dev/null
    /bin/chown "$VDSM_PERMS" "$VDSM_CA"
    /sbin/restorecon "$VDSM_CA"
fi

if [ ! -f "$VDSM_CRT" ]; then
    /bin/cat > "$VDSM_TEMPLATE" <<EOF
organization    = "VDSM Certificate"
cn              = "$VDSM_FQDN"
email           = "root@$VDSM_FQDN"
signing_key
encryption_key
tls_www_server
tls_www_client
EOF
    /usr/bin/certtool --generate-certificate --load-privkey "$VDSM_KEY" \
                      --load-ca-privkey "$VDSM_KEY" \
                      --load-ca-certificate "$VDSM_CA" \
                      --template "$VDSM_TEMPLATE" --outfile "$VDSM_CRT" \
                      2> /dev/null
    /bin/chown "$VDSM_PERMS" "$VDSM_CRT"
    /sbin/restorecon "$VDSM_CRT"
fi

/bin/rm -f "$VDSM_TEMPLATE"
